var zcom = require("../components/winLocation.js");
zcom.QueryString.Initial();
var myDialog = require("./cmodal.js");
var authentication = require("./authentication.js");
var view = require("./views/applyView.js");
var num = require("../components/number.js");
var getVerifyCodeDJS = 60; // 取验证码倒计时
var totalamount;
$verifyBtn = $("#verifyBtn");
$(function() {
    //    zcom.checkBrowser();
    inintUserNameEvent();
    initUserIdEvent();
    inintCreditCardEvent();
    initCVN2Event();
    initTimeNumEvent();
    inintphoneEvent();
    initVerifyBtn();
    inintYZMEvent();
    initYanjingIconEvent();
    initVale();
    $("#submitA").on("touchstart", applyLfqOrder);
    $("#submitApply").on("touchstart", applyLfqOrder2);
    $("#submitCancel").on("touchstart", function() {
        $("#orderTiShi").hide();
    });
    $("#orderTiShi .close_div").on("touchend", function() {
        setTimeout(function() {
            $("#orderTiShi").hide();
        }, 200);

    });
    $("#modalButton").parent().on("touchend", function() {
        myDialog.hideModal();
        event.preventDefault();
    });
    $("#verifyBtn").on("touchstart", getVerifyCode);

    initStyle();
    setSessionStorage();
    setReadOnly();
    countDownTime();
    resetUrl();
    view.spaceFrist();
});


function initVale() {
    var orderIddes = zcom.QueryString.GetValue("orderIddes");
    orderId = $("#orderId").val();
    if (!orderIddes) {
        location.href = "../../installment/jsp/error.jsp?msg=failure";
    }
    totalamount = zcom.QueryString.GetValue("totalamount");
    $("header a").attr("href", sessionStorage.applyUrl1);
}

// 根据设备计算一些样式
function initStyle() {
    setInterval(function() {
        var orderTiShiHeight = parseInt(($("body")[0].scrollHeight - 360) / 2);
        $("#orderTiShi .modal-dialog").css("margin-top", orderTiShiHeight + "px");

    }, 500);

}

// 设置只读
function setReadOnly() {
    var readVal = $("#onlyData").text();
    var readIvalA = [{
        name: "creditName",
        value: "user-name"
    }, {
        name: "cetitype",
        value: ""
    }, {
        name: "creditNo",
        value: "creditCard",
        fun: view.spaceCardNum
    }, {
        name: "idno",
        value: "user-id",
        fun: view.spaceuserId
    }, {
        name: "phoneNo",
        value: "user-phone",
        fun: view.spacePhoneNum
    }, {
        name: "cvv",
        value: "cvn2Num"
    }, {
        name: "validty_period",
        value: "timeNum"
    }];
    for (var i = 0, l = readIvalA.length; i < l; i++) {
        if (readVal.search(readIvalA[i].name) != -1) {
            $("#" + readIvalA[i].value).attr("readonly", "readonly");
            if (readIvalA[i].fun) {
                readIvalA[i].fun();
            }
        }
    }
}


function applyLfqOrder() {
    $("input").blur();
    if ($("#submitA").hasClass("btn_disabled")) {
        return;
    }
    myDialog.showModals("orderTiShi");

}

// 确认申请分期提交表单
function applyLfqOrder2() {
    $("#orderTiShi").hide();
    $("#tishuModal .modal-content").hide();
    $(".modal-content2").show();
    myDialog.showModals();
    var param = getParameters(); // 参数字符形式 
    console.log(param); //把字符串打印到控制台 调试用的  


    try {
        zcom.postAjax(LFQ_ORDER_CREATE_URL, param, retnFunc, true);
    } catch (e) {
        $("#msg_lable").text("网络无法连接");
        $("#tishuModal .modal-content").show();
        $(".modal-content2").hide();
        myDialog.showModals(); // 显示提示框
    }

}

// 回调函数
function retnFunc(retn) {
    var tipmsg = "init";
    var resmsg = "";
    var des_openid = "";



    if (retn.lft_orderinfo_response != undefined) {
        if (retn.lft_orderinfo_response.resp_code == "0000") { //如果成功 
            window.location.href = "../../installment/jsp/result.html?ts_amt=" + totalamount + "&returnurl=" + encodeURI($("#urlrerurn").val());
        } else {
            tipmsg = retn.lft_orderinfo_response.resp_msg;
        }
    } else if (retn.error_business_response && retn.error_business_response.code == "0000") {
        window.location.href = "../../installment/jsp/result.html?ts_amt=" + totalamount + "&returnurl=" + encodeURI($("#urlrerurn").val());
        return;
    } else if (retn.error_business_response && "50,51,52,53".search(retn.error_business_response.code) != -1) {
        // 可修改的提示
        if (retn.error_business_response) {
            resmsg = retn.error_business_response.msg;
            tipmsg = retn.error_business_response.msg;
        } else if (retn.error_response != undefined) {
            resmsg = retn.error_response.resp_code;
            tipmsg = retn.error_response.resp_msg ? retn.error_response.resp_msg : retn.error_response.sub_msg;
        } else if (retn.user_acct_response != undefined) {
            resmsg = retn.user_acct_response.is_black;
            des_openid = retn.des_open_id;
        } else if (retn.error_business_response) {
            tipmsg = retn.error_business_response.sub_msg;
        } else {
            tipmsg = "当前服务请求出错，请重新查询";
        }

        if (resmsg == 'WRONG0001') {
            tipmsg = "短信验证码出错";
        } else if (resmsg == 'WRONG999') {
            tipmsg == "申请服务异常";
        }
    } else {
        var errorCode = retn.error_business_response.code;
        var errorMsg = changeErrorMsg(errorCode)
        if (errorMsg == "" || errorMsg == undefined) {
            errorMsg = "该笔订单支付失败";
        }
        location.href = "../../installment/jsp/error.jsp?msg=" + errorMsg + "&returnurl=" + encodeURI($("#urlrerurn").val());
    }

    // code 为59时失败 跳转到提示页面
    if (retn.error_business_response.code == "59") {
        location.href = "../../installment/jsp/error.jsp?ev=paid&msg=" + tipmsg + "&returnurl=" + encodeURI($("#urlrerurn").val());
    }
    // code 为56时失败 跳转到提示页面
    if (retn.error_business_response.code == "56") {
        location.href = "../../installment/jsp/error.jsp?ev=paid&msg=" + tipmsg + "&returnurl=" + encodeURI($("#urlrerurn").val());
    }

    if (tipmsg != "init") {
        $("#msg_lable").text(tipmsg);
        $(".modal-content").show();
        $(".modal-content2").hide();
        myDialog.showModals(); // 显示提示框
    }
}

// 拼接请求参数
function getParameters() {
    var userName = $("#user-name").val();
    var userId = $("#user-id").val().replace(/ /g, "");
    var CardNum = $("#creditCard").val().replace(/ /g, "");
    var parameters = [{
        name: "phoneNo",
        value: $("#user-phone").val().replace(/ /g, "")
    }, {
        name: "creditName",
        value: userName
    }, {
        name: "idno",
        value: userId
    }, {
        name: "creditNo",
        value: CardNum
    }, {
        name: "cvn2",
        value: $("#cvn2Num").val()
    }, {
        name: "exp",
        value: $("#timeNum").val()
    }, {
        name: "servlet_type",
        value: "create_order"
    }, {
        name: "verifyCode",
        value: $("#verify-code").val()
    }, {
        name: "orderId",
        value: $("#orderId").val()
    }, {
        name: "sign",
        value: $("#signs").val()
    }, {
        name: "tookenkey",
        value: $("#tookenkey").val()
    }]; //请求参数

    card_6th = CardNum.substr(CardNum.length - 6); // 传到付款码页面用于重新生成串码
    return parameters;
}

// 根据后台返回的错误码修改提示语
function changeErrorMsg(errorCode) {

    var codeMsg = {
        //以下为分期操作类返回码
        "4001": "无法获得产品信息",
        "4002": "订单创建失败",
        "4003": "输入有误,请重新输入",
        "4004": "当前订单状态无法重新生成订单",
        "4005": "订单信息不存在",
        "4006": "订单重新生成失败",
        "4007": "扫码商户和进行消费的商户非同一商户,不能消费",
        "4008": "当前订单已失效,请重新生成",
        "4009": "该笔订单正在处理中，请稍后....",
        "4010": "金额不一致，不能消费",
        "4011": "订单消费失败",
        "4012": "当前订单非可消费状态",
        "4013": "该商品不支持部分退货",
        "4014": "退货失败",
        "4015": "无法获取小通分期的商户号,请先配置该商户小通分期的商户号",
        //          "4016":"无法获得总部成本扣率,请先设置n期的总部成本扣率",
        "4016": "无法获得总部成本扣率，暂不支持该分期期数",
        "4017": "无法获得供应商成本扣率",
        "4018": "验签错误",
        "4019": "商户信息不存在",
        "4020": "该笔订单已做过交易,无需重复交易",
        "4021": "该笔订单不允许撤销",
        "4022": "该笔订单超过了允许撤销的日期",
        "4023": "撤销失败",
        "4024": "当前订单已经处于退货审核中,不能撤销",
        "4025": "无法获得总部营业员分成比例,请先设置n期的营业员分成比例",
        "4026": "退货的商户和消费商户非同一商户,不能退货",
        "4027": "无法获取订单商户号",
        //以下为银骏交易失败返回码
        "0101": "交易失败。",
        "0103": "通讯超时",
        "0105": "交易已受理，请稍后查询交易结果",
        "0110": "报文格式错误",
        "0111": "验证签名失败",
        "0112": "重复交易",
        "0113": "身份证格式错误",
        "0114": "手机号格式错误",
        "0115": "CVN格式错误",
        "0116": "有效期格式错误",
        "0117": "该卡不支持分期业务",
        "0118": "商户不支持的分期期数",
        "0119": "卡有效期不足以进行分期支付，请重新换卡",
        "0132": "无此交易权限",
        "0134": "查无此交易",
        "0138": "商户密码错误",
        "0140": "单笔交易金额不在规定范围内",
        "0141": "超过个人借款总金额",
        "0142": "超过个人在单个商户单日交易总金额",
        "0144": "该卡因多次余额不足交易受限",
        "0151": "令牌失效，无效的提交",
        "0152": "用户提交的数据校验出错",
        "0153": "超过有效时间",
        "0170": "持卡人姓名、身份证或手机号输入错误，验证失败",
        "0199": "未知错误",
        "0201": "交易失败",
        "0210": "业务数据错误",
        "0220": "商户不存在",
        "0221": "商户无效",
        "0299": "未知错误",
        "0301": "交易失败",
        "0302": "系统维护中请稍后再试",
        "0303": "交易通讯超时",
        "0304": "交易超时 ",
        "0305": "交易已受理，接收通讯异常",
        "0310": "通讯异常，报文格式错误",
        "0311": "通讯异常，验证签名失败",
        "0312": "重复交易",
        "0313": "通讯异常，交易要素缺失",
        "0314": "批量文件格式错误",
        "0330": "交易失败，请更换其他卡支付",
        "0331": "通讯异常，商户状态不正确",
        "0332": "请使用有银联标识的信用卡",
        "0333": "交易金额超限",
        "0334": "查无此交易",
        "0335": "原交易状态不正确",
        "0336": "与原交易信息不符，请重新操作",
        "0337": "已超过最大查询次数或操作过于频繁",
        "0338": "风险受限",
        "0339": "交易不在受理时间范围内",
        "0340": "绑定关系检查失败",
        "0341": "批量状态不正确，无法下载",
        "0342": "扣款成功但交易超过规定支付时间",
        "0360": "交易失败，详情请咨询您的发卡行",
        "0361": "输入的卡号无效，请确认后输入",
        "0362": "交易失败，发卡银行不支持该交易，请更换其他银行卡",
        "0363": "卡状态不正确",
        "0364": "卡上的余额不足",
        "0365": "输入的密码、有效期或CVN2有误，交易失败",
        "0366": "持卡人身份信息或手机号输入不正确，验证失败",
        "0367": "密码输入次数超限",
        "0368": "您的银行卡暂不支持该业务",
        "0369": "您的输入超时，交易失败",
        "0370": "交易超时",
        "0371": "动态口令或短信验证码校验失败",
        "0372": "尚未开通无卡支付功能，请联系银行开通",
        "0373": "该卡已过有效期",
        "0374": "扣款成功，销账未知",
        "0375": "扣款成功，销账失败",
        "0376": "需要验密开通",
        "0377": "银行卡未开通认证支付",
        "0378": "发卡行交易权限受限，详情请咨询您的发卡行"
    };
    var errorMsg = "";
    if (codeMsg[errorCode]) {
        errorMsg = codeMsg[errorCode];
    }

    return errorMsg;
}


// 禁用或启用按钮
function isDisabledSubmit() {
    var isCnName = authentication.isCnName($("#user-name").val());
    var isSFZNo = authentication.isSFZNo($("#user-id").val().replace(/ /g, ""));
    var isCvn2Num = $("#cvn2Num").val().length < 3 ? false : true;
    var istimeNum = authentication.isTimeNum($("#timeNum").val());
    var isPhone = $("#user-phone").val().replace(/ /g, "").length == 11;
    var isYZM = authentication.isNum($("#verify-code").val(), 6);
    var XYKNum = $creditCard.val().replace(/ /g, "");
    var isXYKNum = authentication.isXYKNum(XYKNum);

    if (isCnName && isSFZNo && isCvn2Num && istimeNum && isPhone && isYZM && isXYKNum) {
        $("#submitA").removeClass("btn_disabled");
        $("#submitA").addClass("btn_primary");
    } else {
        $("#submitA").removeClass("btn_primary");
        $("#submitA").addClass("btn_disabled");
    }
}

// 绑定姓名输入框事件
function inintUserNameEvent() {

    $("#user-name").on("input", function() {
        isDisabledSubmit();
    });
    $("#user-name").on("change  blur", changUserName);
    $("#user-name").on("keyup", function() {
        view.getFocus("#user-id");
    });
}
// 姓名输入完 验证
function changUserName() {
    $userName = $("#user-name");
    var $eventTargetParentNode = $userName.parent().parent();
    var isCnName = authentication.isCnName($userName.val());
    authentication.addOrRemoveErro(true, "userName-erro", "中文名字错误", $eventTargetParentNode);
    if (!isCnName || $userName.val().length > 15) {

        if ($userName.val().length > 15) {
            authentication.addOrRemoveErro(false, "userName-erro", "中文名字长度必须小于15个字", $eventTargetParentNode);
        } else {
            var tsCount = "中文名字错误";
            if ($userName.val() == "") {
                tsCount = "请输入中文名";
            }
            authentication.addOrRemoveErro(isCnName, "userName-erro", tsCount, $eventTargetParentNode);
        }
    }

}

// 绑定身份证号输入框事件
function initUserIdEvent() {
    $("#user-id").on("change blur input", changeUserId);
    $("#user-id").on("input", function() {
        $(this).val($(this).val().toUpperCase());
        deleteNoNumberX($(this)[0]);
        if (!($("#cvn2Num").val().length == 3)) {
            view.getFocus("#cvn2Num");
        }
        isDisabledSubmit();
    });
    $("#user-id").on("keyup", function() {
        view.deleteSpace(event.keyCode, "#user-id");
        if (event.keyCode != 8 && event.keyCode != 37 && event.keyCode != 39) {
            view.spaceuserId();
        }
        view.getFocus("#creditCard");
    });
}

function deleteNoNumberX(obj) {
    var reg = /[^\dX\*\s]/;
    if (reg.test(obj.value) || obj.value == "") {
        obj.value = obj.value.replace(/[^\dX\*\s]/g, "");
    }
    if (/[\*]/.test(obj.value)) {
        obj.value = obj.value.replace(/[\*]/g, "X");
    }
}


// 身份者输入完毕验证 
function changeUserId() {
    var $eventTargetParentNode = $("#user-id").parent().parent();
    var isSFZNo = authentication.isSFZNo($("#user-id").val().replace(/  /g, ""));
    var tssfzCount = "身份证号码格式错误";
    if ($("#user-id").val() == "") {
        tssfzCount = "请输入身份证号";
    }
    authentication.addOrRemoveErro(isSFZNo, "sfz-erro", tssfzCount, $eventTargetParentNode);
}

// 绑定信用卡输入事件
function inintCreditCardEvent() {
    $creditCard = $("#creditCard");
    $creditCard.on("change blur input", changeCreditCard);
    $creditCard.on("keyup", function() {
        view.deleteSpace(event.keyCode, "#creditCard");
        if (event.keyCode != 8 && event.keyCode != 37 && event.keyCode != 39) {
            view.deleteNoNumber(this);
            view.spaceCardNum();
        }
        view.getFocus("#cvn2Num");
    });
    $creditCard.on("input", function() {
        isDisabledSubmit();
    });
}

// 信用卡输入完毕验证
function changeCreditCard() {
    $creditCard = $("#creditCard");
    view.spaceCardNum();
    var $eventTargetParentNode = $creditCard.parent().parent();
    var XYKNum = $creditCard.val().replace(/ /g, "");
    var isXYKNum = authentication.isXYKNum(XYKNum);
    var tsxykCount = "信用卡格式错误";
    if ($creditCard.val() == "") {
        tsxykCount = "请输入信用卡号";
    }
    authentication.addOrRemoveErro(isXYKNum, "isXYKNum-erro", tsxykCount, $eventTargetParentNode);
}

// 绑定CVN2输入框事件
function initCVN2Event() {
    $cvn2Num = $("#cvn2Num");
    $cvn2Num.on("change blur", changeCvn2Num);
    $cvn2Num.on("input", function() {
        this.value = this.value.replace(/[^\d]/g, "");
        var cvn2NumVal = new String($cvn2Num.val());
        if (cvn2NumVal.length > 3) {
            $cvn2Num.val(cvn2NumVal.substr(0, 3));
        }
        isDisabledSubmit();
    });
    $cvn2Num.on("keyup", function() {
        view.getFocus("#timeNum");
    });

}
//验证CVN2 格式
function changeCvn2Num() {
    var cvn2Num = $("#cvn2Num").val();
    var isCvn2Num = cvn2Num.length < 3 ? false : true;
    var $eventTargetParentNode = $("#cvn2Num").parent().parent();
    var tscvnCount = "CVN2格式错误";
    if (cvn2Num == "") {
        tscvnCount = "请输入信用卡CVN2";
    }
    authentication.addOrRemoveErro(isCvn2Num, "isCvn2Num-erro", tscvnCount, $eventTargetParentNode);
}

// 绑定时间输入框事件
function initTimeNumEvent() {
    $timeNum = $("#timeNum");
    $timeNum.on("change blur", changeTimeNum);
    $timeNum.on("input", function() {
        view.deleteNoNumber(this);
        var timeNumVal = new String($timeNum.val());
        if (timeNumVal.length > 4) {
            $timeNum.val(timeNumVal.substr(0, 4));
        }
        isDisabledSubmit();
    });
    $timeNum.on("keyup", function() {
        view.getFocus("#user-phone");
    });
}

// 验证有效时间
function changeTimeNum() {
    var timeNum = $("#timeNum").val();
    var istimeNum = authentication.isTimeNum(timeNum);
    var $eventTargetParentNode = $("#timeNum").parent().parent();
    var tsTimeCount = "有效时间格式错误";
    if (timeNum == "") {
        tsTimeCount = "请输入信用卡有效期";
    }
    authentication.addOrRemoveErro(istimeNum, "istimeNum-erro", tsTimeCount, $eventTargetParentNode);
}

function initVerifyBtn() {
    if (getVerifyCodeDJS == 60 && $("#user-phone").val().replace(/ /g, "").length == 11) {
        $verifyBtn.removeClass("disabled");
    }
}

// 绑定手机号事件
function inintphoneEvent() {
    $("#user-phone").on("change blur input", changeUserPhone);
    $("#user-phone").on("keyup", function() {
        view.deleteSpace(event.keyCode, "#user-phone");
        if (event.keyCode != 8 && event.keyCode != 37 && event.keyCode != 39) {
            view.deleteNoNumber(this);
            view.spacePhoneNum();
        }

        if (getVerifyCodeDJS == 60 && $("#user-phone").val().replace(/ /g, "").length == 11) {
            $verifyBtn.removeClass("disabled");
        }
        if (event.keyCode == 13) {
            $("input").blur();
        }
        isDisabledSubmit();
    });
}
//电话输入完 验证
function changeUserPhone() {
    var userPhone = $("#user-phone").val().replace(/ /g, "");
    var $eventTargetParentNode = $("#user-phone").parent().parent();
    var isPhone = !(userPhone.length < 11);
    var tsPhoneCount = "手机号码错误";
    if ($("#user-phone").val() == "") {
        tsPhoneCount = "请输入手机号";
    }
    authentication.addOrRemoveErro(isPhone, "phoneNum-erro", tsPhoneCount, $eventTargetParentNode);
}

//请求 验证码
function getVerifyCode() {


    if ($verifyBtn.hasClass("disabled")) { //60秒之内
        return;
    } else { //发送短信 禁用60秒
        //发送短信
        $verifyBtn.addClass("disabled");
        $verifyBtn.text("重新获取(" + getVerifyCodeDJS + "S)");
        var id_no = $("#user-id").val().replace(/ /g, "");
        var isIdNo = authentication.isSFZNo(id_no);
        if (!isIdNo) {
            $("#msg_lable").text("身份证号码错误");
            $("#tishuModal .modal-content").show();
            $("#tishuModal .modal-content2").hide();
            myDialog.showModals("tishuModal"); // 显示提示框
            return;
        }


        var setIntervarHandle = setInterval(function() {
            getVerifyCodeDJS--;
            $verifyBtn.text("重新获取(" + getVerifyCodeDJS + "s)")
            if (getVerifyCodeDJS == 0) {
                $verifyBtn.text("重新获取");
                clearInterval(setIntervarHandle);
                $verifyBtn.removeClass("disabled");
                getVerifyCodeDJS = 60;
            };
        }, 1000);

        getAjaxCode(setIntervarHandle);
    }
}

// 发送验证码请求
function getAjaxCode(setIntervarHandle) {
    var url = LFQ_SMS_SEND_URL;
    var hp_no = $("#user-phone").val().replace(/ /g, "");
    var id_no = $("#user-id").val().replace(/ /g, "");
    var param = {
        hp_no: hp_no,
        orderid: orderId,
        idno: id_no
    };
    zcom.getAjax(url, param, function(retn) {
        console.log("验证码请求结果");
        console.dir(retn);
        if (retn.code == "0") {
            $verifyBtn.text("重新获取");
            $verifyBtn.removeClass("disabled");
            clearInterval(setIntervarHandle);
            $(".modal-content2").hide();
            myDialog.showBodalBody(retn.msg, "tishuModal");
        }
    }, true);
}


// 绑定验证码事件
function inintYZMEvent() {
    var verifyCode = $("#verify-code");
    verifyCode.on("change blur", changeYZM);
    verifyCode.on("input", function() {
        view.deleteNoNumber(this);
        view.getFocus("#submitA");
        isDisabledSubmit();
    });

}
// 验证码输完后验证提示
function changeYZM() {
    var verifyCode = $("#verify-code");
    var $eventTargetParentNode = verifyCode.parent().parent();
    var isNum = authentication.isNum(verifyCode.val(), 6);
    var tsNumCount = "验证码错误";
    if (verifyCode.val() == "") {
        tsNumCount = "请输入验证码";
    }
    authentication.addOrRemoveErro(isNum, "yzm-erro", tsNumCount, $eventTargetParentNode);
}


// 查看输入CVN2事件
function initYanjingIconEvent() {
    $(".yanjing_icon").on("touchstart", function() {
        setBackground("yanjing2_icon.png");
        $("#cvn2Num").attr("type", "number");
    });
    $(".yanjing_icon").on("touchend", function() {
        setTimeout(function() {
            setBackground("yanjing_icon.png");
            $("#cvn2Num").attr("type", "password");
        }, 3000);
    });

    function setBackground(pngName) {
        $(".yanjing_icon").css("background", 'url("../../installment/images/' + pngName + '")');
        $(".yanjing_icon").css("background-repeat", 'no-repeat');
        $(".yanjing_icon").css("background-position", '5px 5px');
        $(".yanjing_icon").css("background-size", '23px 14px');
    }
}

function setSessionStorage() {
    sessionStorage.returnUrl = $("#urlrerurn").val();
}

function resetUrl() {
    var newUrl = location.href.split("?")[0];
    history.pushState({
        title: "支付网关"
    }, "支付网关", newUrl);
}

// 到计时 30 分钟后跳转到订单失效页面
function countDownTime() {
    var oldTime = (new Date()).getTime();
    var countDownhadle = setInterval(function() {
        var newTime = (new Date()).getTime();
        if (newTime - oldTime > 1790000) {
            clearInterval(countDownhadle);
            location.href = "../../installment/jsp/error.jsp?time=out";
        }
    }, 1000);
}